package cn.yll.order.controller;


import cn.yll.api.order.request.OrderRequest;
import cn.yll.api.order.response.GoodResponse;
import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.module.PageModel;
import cn.yll.common.module.PageRequest;
import cn.yll.common.module.RestModel;
import cn.yll.common.utils.CopierUtil;
import cn.yll.api.util.RestUtil;
import cn.yll.order.business.GoodBusiness;
import cn.yll.order.entity.GoodsEntity;
import cn.yll.order.service.IGoodsService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


/**
 * <p>
 * 商品信息表 前端控制器
 * </p>
 *
 * @author yll
 * @since 2022-08-03
 */
@RestController
@Api(tags = "商品信息表相关接口")
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private GoodBusiness goodBusiness;

    @PostMapping("addNewGood")
    @ApiOperation(value = "注册商品接口")
    public RestModel<GoodsEntity> addNewGood(@RequestBody GoodsEntity entity) {
        if (Objects.isNull(entity)) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        goodsService.save(entity);
        return RestUtil.sucess(entity);
    }

    @PostMapping("/findGoodsByPage")
    @ApiOperation(value = "分页查询商品列表")
    public RestModel<PageModel<GoodResponse>> findGoodsByPage(@RequestBody PageRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getPageNum()) || Objects.isNull(request.getPageSize())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }

        Page<GoodsEntity> entityPage = goodsService.page(new Page<>(request.getPageNum(), request.getPageSize(), true), Wrappers.lambdaQuery());
        return RestUtil.sucess(new PageModel<>((int) entityPage.getTotal(), CopierUtil.convertList(entityPage.getRecords(), GoodResponse.class)));
    }

    @PostMapping("checkPriceAndReduceNum")
    @ApiOperation(value = "用户下单检查页面价格并扣减商品库存接口", notes = "状态码200表示校验扣减成功")
    public RestModel<?> checkPriceAndReduceNum(@RequestBody OrderRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getUserId()) || CollectionUtils.isEmpty(request.getLines())) {
            return RestUtil.error(BsErrEnum.PARAM_EMPTY);
        }
        goodBusiness.checkPriceAndReduceNum(request.getLines());
        return RestUtil.sucess();
    }
}
